package com.moyuwanjia.Dao.impl;

import com.moyuwanjia.Dao.AccountDao;
import com.moyuwanjia.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 摸鱼丸加~
 * @create 2022-07-17 11:33
 * 以注解的方式来解决重复代码问题
 *
 */
@Repository(value = "accountDao02")
public class AccountDaoImpl02 implements AccountDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> query = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return query.isEmpty()?null:query.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> query = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (query.isEmpty()) return null;
        if (query.size()>1) throw new RuntimeException("结果集不唯一");
        return query.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set name = ?,money = ? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}
